<template>
    <div class="w-full">
        <el-row>
            <el-col :span="2">
                <el-text class="mx-1" size="large" type="primary">聊天室</el-text>
            </el-col>
            <el-col :span="6">
                <el-text class="mx-1" type="success">当前在线人数 [{{ online }}]</el-text>
            </el-col>
        </el-row>
        <el-tabs type="border-card" class="mt-2" v-model="activeName">
            <el-tab-pane label="对话" name="talk">
                <el-row class="mt-5">
                    <el-col>
                        <el-scrollbar ref="scrollbarRef" height="580">
                            <div ref="innerRef">
                                <div v-for="(item, index) in list" :key="item" class="mt-5">
                                    <el-row v-if="item?.name == 'AI'">
                                        <el-col :span="1">
                                            <el-avatar> {{ item.name }} </el-avatar>
                                        </el-col>
                                        <el-col :span="15">
                                            <el-text class="mx-1" type="info" size="small">{{ item.datetime }}</el-text>
                                        </el-col>
                                    </el-row>
                                    <el-row v-else>
                                        <el-col :span="3" :offset="20">
                                            <el-text class="mx-1" type="info" size="small">{{ item.datetime }}</el-text>
                                        </el-col>
                                        <el-col :span="1">
                                            <el-avatar> {{ item.name }} </el-avatar>
                                        </el-col>
                                    </el-row>
                                    <el-row v-if="item?.name == 'AI'">
                                        <el-col :span="1"></el-col>
                                        <el-col :span="15">
                                            <el-card shadow="always">{{ item.content }}</el-card>
                                        </el-col>
                                    </el-row>
                                    <el-row v-else>
                                        <el-col :span="15" :offset="8">
                                            <el-card shadow="always">{{ item.content }}</el-card>
                                        </el-col>
                                        <el-col :span="1"></el-col>
                                    </el-row>
                                </div>
                            </div>
                        </el-scrollbar>
                    </el-col>
                </el-row>
                <el-affix position="bottom" :offset="60" class="mt-4">
                    <el-row :gutter="5" class="mt-5">
                        <el-col :span="18">
                            <el-input v-model="msg" placeholder="" clearable>
                            </el-input>
                        </el-col>
                        <el-col :span="6">
                            <el-button type="success" @click="sendMesage(msg)">发送</el-button>
                        </el-col>
                    </el-row>
                </el-affix>
            </el-tab-pane>
            <el-tab-pane label="语义订单" name="semantics">
                <el-row class="mt-5">
                    <el-col>
                        <el-scrollbar ref="scrollbarRef1" height="580">
                            <div ref="innerRef1">
                                <div v-for="(item, index) in list1" :key="item" class="mt-5">
                                    <el-row v-if="item?.name == 'AI'">
                                        <el-col :span="1">
                                            <el-avatar> {{ item.name }} </el-avatar>
                                        </el-col>
                                        <el-col :span="15">
                                            <el-text class="mx-1" type="info" size="small">{{ item.datetime }}</el-text>
                                        </el-col>
                                    </el-row>
                                    <el-row v-else>
                                        <el-col :span="3" :offset="20">
                                            <el-text class="mx-1" type="info" size="small">{{ item.datetime }}</el-text>
                                        </el-col>
                                        <el-col :span="1">
                                            <el-avatar> {{ item.name }} </el-avatar>
                                        </el-col>
                                    </el-row>
                                    <el-row v-if="item?.name == 'AI'">
                                        <el-col :span="1"></el-col>
                                        <el-col :span="15">
                                            <el-card shadow="always">{{ item.content }}</el-card>
                                        </el-col>
                                    </el-row>
                                    <el-row v-else>
                                        <el-col :span="15" :offset="8">
                                            <el-card shadow="always">{{ item.content }}</el-card>
                                        </el-col>
                                        <el-col :span="1"></el-col>
                                    </el-row>
                                </div>
                            </div>
                        </el-scrollbar>
                    </el-col>
                </el-row>
                <el-affix position="bottom" :offset="60" class="mt-4">
                    <el-row :gutter="5" class="mt-5">
                        <el-col :span="18">
                            <el-input v-model="msg1" placeholder="" clearable>
                            </el-input>
                        </el-col>
                        <el-col :span="6">
                            <el-button type="success" @click="sendMesage(msg1)">发送</el-button>
                        </el-col>
                    </el-row>
                </el-affix>
            </el-tab-pane>
        </el-tabs>

    </div>

</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useDateFormat, useNow } from '@vueuse/core'
import { ElMessage } from 'element-plus'; // 假设您正在使用 Element Plus  
const store = useMainStore();
const datetime = ref(useDateFormat(useNow(), 'YYYY-MM-DD HH:mm:ss'))
const socket = ref(null);
const activeName = ref('talk')
const online = ref() //在线人数
const message = ref({}); // 初始化消息对象  
const name = store.user?.account
const list = ref([]); // 假设这是您用来存储消息的列表
const list1 = ref([]); // 假设这是您用来存储消息的列表
const msg = ref('')
const msg1 = ref('')
const scrollbarRef = ref() // 滚动条实例
const scrollbarRef1 = ref() // 滚动条实例
const innerRef = ref() // 内部实例
const innerRef1 = ref() // 内部实例
/**
 * 控制滚动条滚动到容器的底部
 */
async function setScrollToBottom() {
    // 注意：需要通过 nextTick 以等待 DOM 更新完成
    await nextTick()
    if (activeName.value === "talk") {
        const max = innerRef.value?.clientHeight + 10
        scrollbarRef.value?.setScrollTop(max)
    } else {
        const max = innerRef1.value?.clientHeight + 10
        scrollbarRef1.value?.setScrollTop(max)
    }
}
const sendMesage = (m, type) => {
    if (!m) {
        ElMessage.warning("发送的消息不能为空");
        return;
    }
    if (!name) {
        ElMessage.warning("未登录");
        return;
    } else {
        message.content = m;
        message.name = name;
        message.datetime = datetime.value;
        if (activeName.value === 'talk') {
            message.type = 'talk';
            list.value.push(JSON.parse(JSON.stringify(message)));
        } else {
            message.type = 'semantics';
            list1.value.push(JSON.parse(JSON.stringify(message)));
        }
        socket.value.send(JSON.stringify(message));
        setScrollToBottom()
    }
}
// 创建一个函数来初始化 WebSocket 连接  
function initWebSocket() {
    list.value = []
    list1.value = []
    let message = {}
    message.content = "请问有什么可以帮助你的嘛";
    message.name = "AI";
    message.datetime = datetime.value;
    message.type = 'talk';
    list.value.push(message);
    message.type = 'semantics';
    message.content = "需要我为你提供什么服务";
    list1.value.push(message);
    if (!name) {
        return;
    }
    const wsurl = `ws://localhost:8080/websocket/${name}`;
    socket.value = new WebSocket(wsurl);

    socket.value.onopen = () => {
        ElMessage.success("Socket连接成功");
    };

    socket.value.onmessage = (event) => {
        if (event?.data) {
            try {
                const data = JSON.parse(event.data);
                message.value = data;
                if (data?.type === "init") {
                    online.value = data?.data
                    return;
                } else if (data?.type === "error") {
                    ElMessage.error(data?.data)
                    return;
                } else {
                    if (data?.orders) {
                        let orderMessage = []
                        data?.orders.forEach(o => {
                            let keywords = o.keyWords
                            orderMessage.push(keywords);
                        })
                        message.value.content = orderMessage.join(', ')
                    } else if (!data.content) {
                        message.value.content = "暂无服务内容"
                    }
                    if (activeName.value === 'talk') {
                        message.value.type = 'talk';

                        list.value.push({ ...message.value });
                    } else {
                        message.value.type = 'semantics';
                        list1.value.push({ ...message.value });
                    }
                    setScrollToBottom()
                }
            } catch (error) {

            }
        }
    };

    socket.value.onerror = (error) => {
        ElMessage.error("网络连接错误");
    };
}

// 在组件挂载时初始化 WebSocket  
onMounted(() => {
    initWebSocket();
});

// 在组件卸载时关闭 WebSocket  
onUnmounted(() => {
    if (socket.value) {
        socket.value.close();
        socket.value = null;
        ElMessage.error("Socket断开");
    }
});  
</script>